package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Region;
import cn.wolfcode.luowowo.query.RegionQuery;
import cn.wolfcode.luowowo.repository.RegionRepository;
import cn.wolfcode.luowowo.service.IRegionService;
import cn.wolfcode.luowowo.util.LogicException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class RegionServiceImpl  implements IRegionService{
    @Autowired
    private RegionRepository regionRepository;
    @Autowired
    private MongoTemplate template;
    @Override
    public List<Region> list() {
        return regionRepository.findAll();
    }

    @Override
    public Region selectOne(String id) {
        return regionRepository.findById(id).orElse(null);
    }

    @Override
    public void update(Region region) {
        regionRepository.save(region);
    }

    @Override
    public void save(Region region) {
        regionRepository.save(region);
    }

    @Override
    public Page<Region> query(RegionQuery qo) {
        //创建查询对象
        Query query =new Query();
        //总记录数
        long count = template.count(query, Region.class);
        if(count==0){
            return Page.empty();
        }
        //页面显示数据集合list
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.ASC,"_id");
        query.with(pageable);
        List<Region> list  = template.find(query,Region.class);

        return new PageImpl<>(list,pageable,count);
    }

    @Override
    public void saveOrUpdate(Region region) {
        if(!StringUtils.hasLength(region.getName())){
            throw new LogicException("名字不能为空");
        }
        if(StringUtils.hasLength(region.getId())){
            //注意:mongodb更新是全量更新,操作是先查,再替换,再更新
            //此处不需要是因为修改的参数跟数据库的刚好一样
            this.update(region);
        }else{
            this.save(region);
        }
    }

    @Override
    public void delete(String id) {
        regionRepository.deleteById(id);
    }

    @Override
    public void changeHotValue(String id, int hot) {
        //通过id查询相关区域
        Region region = this.selectOne(id);
        region.setIshot(hot);
        this.update(region);
    }

    @Override
    public List<Region> queryHot() {
       return regionRepository.findByIshotOrderBySequenceAsc(Region.STATE_HOT);

    }

}
